<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Cache;

/**
 * 阅读任务对应数据量数据
 * Class ArticleModel
 * @package app\common\model
 */
class ReadingTaskDatabase extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'reading_task_database';


    /**
     * 获取阅读任务下的作品数据库列表
     * @param task_id string 活动id
     */
    public function getReadingTaskDatabaseList($task_id)
    {
        $res = $this->from($this->getTable() . ' as r')
            ->select('r.id', 'd.id as database_id', 'd.name', 'r.create_time')
            ->join('competite_activity_database as d', 'd.id', '=', 'r.database_id')
            ->where('r.task_id', $task_id)
            ->where('d.is_del', 1)
            ->where('d.is_play', 1)
            ->orderByDesc('r.create_time')
            ->get()
            ->toArray();
        return $res;
    }


    /**
     * 判断指定用户是否可以参加
     * @param task_id
     * @param user_id
     */
    public function getAppointUser($task_id, $user_id)
    {
        return $this->where('task_id', $task_id)->where('user_id', $user_id)->first();
    }

    /**
     * 获取指定用户
     * @param task_id 活动id
     */
    public function getAppointUserInfo($task_id, $keywords, $limit = 10)
    {
        $res = $this->from('user_info as u')
            ->select('b.id', 'u.id as user_id', 'u.account_id', 'b.create_time', 'w.nickname', 'w.head_img')
            ->join('user_wechat_info as w', 'w.id', '=', 'u.wechat_id')
            ->join('picture_live_appoint_user as b', 'b.user_id', '=', 'u.id')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('w.nickname', 'like', "%$keywords%");
                }
            })
            // ->where(function ($query) use ($start_time, $end_time) {
            //     if ($start_time && $end_time) {
            //         $query->whereBetween('b.create_time', [$start_time, $end_time]);
            //     }
            // })
            ->where('b.task_id', $task_id)
            ->orderByDesc('b.create_time')
            ->paginate($limit)
            ->toArray();
        return $res;
    }

    /**
     * 添加
     * @param $data 数据
     */
    public function add($data, $field = [])
    {
        $res = $this->where('task_id', $data['task_id'])->where('user_id', $data['user_id'])->first();
        if ($res) {
            return true;
        }

        $this->task_id = $data['task_id'];
        $this->user_id = $data['user_id'];
        return $this->save();
    }
}
